import { Button, Card, Row, Col, Tooltip, Tag, Modal, message, Spin  } from 'antd';
import { WeaTag, WeaDialog, WeaSearchGroup, WeaFormItem, WeaNewScroll, WeaInput, WeaSelectGroup, WeaSelect, WeaAlertPage,
  WeaTableEditable,WeaLocaleProvider,
} from 'ecCom';
import { observer, inject } from 'mobx-react';
import { WeaForm, WeaSwitch, WeaTableNew } from 'comsMobx';
import { toJS } from 'mobx';
import WeesoSearchSet from './weesoSearchSet';
const WeaTable = WeaTableNew.WeaTable;
const allstore = ['routing','weesoStore', 'weesoSeachSetStore'];
const getLabel = WeaLocaleProvider.getLabel;

@inject(...allstore)
@observer
export default class WessoRecords extends React.Component {
  static defaultProps = {
    prefixCls: 'esearch-tags-container',
  };
  constructor(props) {
    super(props);
    let pageuuid = this.props.routing&&this.props.routing.location&&this.props.routing.location.query&&this.props.routing.location.query.page_uuid || '-9999';
    this.state = {
      lvisible: false,
      page_uuid: pageuuid || '05640dad-cfdc-482f-9c70-a89b54e0daa6',
      form: new WeaForm(),
      conditioninfo: [],
      recentBrowsing: [],
      value: [], 
      formValue: {
        keywords: '',
        select: '',
        CREATEDATE: []
      },
      selectVal: '1',
      saveLoading: false,
      keySpining: false,
      recentSping: false,
      maintenanceKeyDialogHeight: 500,
      cardHeight: 200,
    };
    this.props.weesoSeachSetStore.setState({ page_uuid: pageuuid });
    this.maintenanceKeyRef = React.createRef();
    this.cardContentRef = React.createRef();
  }

  componentDidMount() {
    const { doSearch, setState, skipSearchParams,  } = this.props.weesoStore;
    const { page_uuid } = this.state;
    let params = skipSearchParams;
    params = {
      ...params,
      page_uuid: page_uuid
    };
    setState({skipSearchParams: params});
    this.getRecentData();
    // this.getBase('didmount');
    window.dorefreshRecentBroTags = this.getRecentData;
    const { doSaveSearchTag } = this.props.weesoSeachSetStore;
    // doSaveSearchTag();
  }

  componentDidUpdate = () => {
    if(this.maintenanceKeyRef && this.maintenanceKeyRef.current && this.maintenanceKeyRef.current.state) {
      if(this.maintenanceKeyRef.current.state.height !== this.state.maintenanceKeyDialogHeight ) {
        this.setState({ maintenanceKeyDialogHeight: this.maintenanceKeyRef.current.state.height });
      }
    }
  }

  getBase = (type) => {
    const { doSearch, setState } = this.props.weesoStore;
    this.setState({keySpining: true});
    const { formValue, page_uuid } = this.state;
    false && API.getBaseData({
      page_uuid: page_uuid
    }).then(res => {
      let selectVal = res && res.contentType && res.contentType[0] && res.contentType[0].key || '';
      let form = {
        ...formValue,
        select: selectVal
      };
      selectVal != '' && setState({ecodeTitleParams: res, defalutMoreKey: selectVal });
      if(type === 'didmount') {
        this.setState({ keySpining: false, formValue: form });
      } else {
        this.setState({ keySpining: false });
      }
    });
  }

  getRecentData = () => {
    const id = this.state.page_uuid;
    if(localStorage.getItem('wesoEDRecentBrowsing')) {
      let recentBrowsingObj = JSON.parse(localStorage.getItem('wesoEDRecentBrowsing'));
      recentBrowsingObj[id] && this.setState({ recentBrowsing: recentBrowsingObj[id], recentSping: true });
    }
    setTimeout(() => {
      this.setState({ recentSping: false })
    }, 300);
  }

  pushRouter = (inputValue) => {
    let page_uuid = this.props.routing.location && this.props.routing.location.query &&  this.props.routing.location.query.page_uuid;
    let { search } = this.props.routing.location;
    if(search) {
      if(search.search(/&value=(.*)&/) < 0) {
        search = search.replace(/&value=(.*)/, `&value=${inputValue}`);
      } else {
        search = search.replace(/&value=(.*)&/, `&value=${inputValue}&`);
      }
    }
    this.props.routing.push(`/main/esearch/result${search}`);
  }

  getTags = (text) => {
    return (
      <div className='esearch-tag'>
        <span>{ text }</span>
      </div>
    );
  }

  setTags = (tags, type) => {
    const { weesoSeachSetStore } = this.props;
    const { doSearch, setState, skipSearchParams, tagsDatas:{conditionSpining} } = this.props.weesoStore;
    const { delSearchTag, delHistorySearch, getCustompageBaseDatas, page_uuid, getAdConditions, searchTagParams  } = this.props.weesoSeachSetStore;
    // const { page_uuid } = this.state;
    let arr = [];
    let style = {marginRight: 20, marginBottom: 20, };
    let H = window.innerHeight * 0.33;
    const { keySpining, recentSping } = this.state;

    const WeaTagCom = (props) => {
      return <div className="esearch-tag" onClick={(e) => {
        typeof props.onClick === 'function' && props.onClick(e);
        e.stopPropagation && e.stopPropagation();
        e.cancelBubble = true;
      }}>
        <span>{props.text}</span>
        {props.closable === true && <i className="esearch-tag-com icon-coms-Clear" onClick={(e) => {
          this.deleteRecords(getLabel(127574, '确定删除吗？'),() => {
            typeof props.onClose === 'function' && props.onClose(e);
          });
          e.stopPropagation && e.stopPropagation();
          e.cancelBubble = true;
        }} />}
      </div> 
    }
    Object.prototype.toString.call(tags) === '[object Array]' && tags.forEach(res => {
      if(type == 'recentBro') {
        arr.push(
          <WeaTagCom ecId={`${this && this.props && this.props.ecId || ''}_WeaTagCom@wognn4@${res.key}`} 
            text={res.name}
            closable={res.canDel}
            onClick={(e) => { 
              let extraParams = {
                ...skipSearchParams,
                page_uuid: page_uuid,
                searchTagId: ''
              };
              weesoSeachSetStore.setState({searchTagParams: {}, homeToResultPage: true, recordType: '' }, () => {
                this.pushRouter(res.searchKey);
                setState({ inputValue: res.searchKey, skipSearchParams: extraParams }, ()=>doSearch());
              });
            }}
            onClose={(e) => { 
              delHistorySearch({ id: res.key }, () => {
                getCustompageBaseDatas({
                  page_uuid: page_uuid,
                  cuspage_type: '2'
                });
              });
            }}
          />
        );
      } else {
        arr.push(
          <WeaTagCom ecId={`${this && this.props && this.props.ecId || ''}_WeaTagCom@1szyeq@${res.key}`} 
            text={res.name}
            closable={res.canDel}
            onClick={(e) => { 
              let extraParams = {
                ...skipSearchParams,
                page_uuid: page_uuid,
                searchTagId: res.key
              };
              setState({ inputValue: res.searchKey, skipSearchParams: extraParams }, ()=>{ 
                doSearch();
                getAdConditions({ id: res.key||'', search_json: JSON.stringify(this.filterParams()) });
              });
              weesoSeachSetStore.setState({ searchTagParams: res, homeToResultPage: true, recordType: 'commonContion' }, () => {
                this.pushRouter(res.searchKey);
              });
            }}
            onClose={(e) => { 
              delSearchTag({ id: res.key }, () => {
                getCustompageBaseDatas({
                  page_uuid: page_uuid,
                  cuspage_type: '3'
                });
              });
            }}
          />
        );
      }
    });
    if(arr.length === 0) {
      arr.push(
        this.getNodata(type)
      );
    }
    return (
      <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@u39r33`}
        height={this.state.cardHeight}
      >
        { arr }
      </WeaNewScroll>
    )
  }

  filterParams = () => {
    let { browserKeyArr, adSearchForm } = this.props.weesoSeachSetStore;
    const formParams = adSearchForm.getFormParams();
    let search_json = { ...formParams };
    delete search_json.showorder;
    delete search_json.tagName;
    delete search_json.tagTitle;
    browserKeyArr = toJS(browserKeyArr);
    Object.keys(search_json).forEach(key => {
      if(browserKeyArr.some(v => v === key)) {
        if(search_json[key] !== '') {
          search_json[key] = search_json[key].split(',');
        } else {
          delete search_json[key];
        }
      }
    });
    return search_json;
  }

  getNodata = (type) => {
    let iconsProps = {
			icon : <i className="icon-coms-blank" />,
			iconSize : 94,
			paddingTop : '5%'
    }
    const msg = type === 'recentBro' ? getLabel('524269','暂无搜索记录')  : getLabel('524270','暂无搜索条件') ;
    return <div className={"esearch-no-data"}>
      <img width={94} height={72} src={require('../util/img/nodata.png')} />
      <div>
        {msg}
      </div>
    </div>
  }

  onCloseCommonDialog = () => {
    this.setState({ lvisible: false });
    const { setState } = this.props.weesoSeachSetStore;
    setState({ searchDefineCommonInputVal: '', searchDefinePageInputVal: '' });
  }

  setMaintanceKey = () => {
    let fields = [];
    const { maintenanceKeyDialogHeight } = this.state;
    const { lvisible, saveLoading } = this.state;
    let buttons = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7q5os1@onSave`} type="primary" disabled={saveLoading} loading={saveLoading} onClick={() => this.onSave()}>{getLabel('30986','保存') }</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@sj27x1@onCancel`} type="ghost" onClick={() => this.setState({ lvisible: false })}>{getLabel('31129','取消') }</Button>
    ];
    fields.push(
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@19xj03@maintenanceKey`}
        className={'esearch-maintenanceKey'}
        ref={this.maintenanceKeyRef}
        title={getLabel('524085','常用条件设置') }
        icon="icon-coms-ws"
        iconBgcolor="#A0B0BA"
        onCancel={this.onCloseCommonDialog}
        visible={lvisible}
        style={{ width: 790, height: maintenanceKeyDialogHeight }}
        // buttons={buttons}
        hasScroll
      >
        <WeesoSearchSet ecId={`${this && this.props && this.props.ecId || ''}_WeesoSearchSet@gm29i2@WeesoSearchSet`} lvisible={lvisible} page={'maintenanceKey'} maintenancekeyref={this.maintenanceKeyRef} dialogheight={maintenanceKeyDialogHeight} />
      </WeaDialog>
    )

    return fields;
  }

  getSearchEdittable = () => {
    const { tagsDatas:{conditionSetTableStore} } = this.props.weesoStore;
    return (
      <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@dbezlp`}
        comsWeaTableStore={conditionSetTableStore}
      ></WeaTable>
    );
  }

  onSave = () => {
    let _this = this;
    const { page_uuid, formValue } = this.state;
    let keys = formValue.keywords.replace(/(^\s*)|(\s*$)/g, ""); 
    let params = {
      page_uuid: page_uuid,
      tagName: formValue.keywords,
      search_type: formValue.select,
      search_json: JSON.stringify(formValue.CREATEDATE)
    };

    if(keys == '') {
      message.error(getLabel('524259','必填项未填写!'));
    } else {
      this.setState({saveLoading: true});
      false && API.doSaveSearchTag(params).then(res => {
        if(res && res.false && API_status && res.status == '1') {
          _this.setState({saveLoading: false, lvisible: false});
          _this.getBase();
          message.success(getLabel('22619','保存成功') );
        } else {
          message.error(getLabel('22620','保存失败'));
        }
      });
    }
  }

  onChange = (key, val) => {
    let { baseDadas: { timeSag } } = this.props.weesoStore;
    timeSag = toJS(timeSag);
    const { formValue } = this.state;
    let obj = formValue;
    
    if(key === 'CREATEDATE' && val[0]) {
      
      let dateRange = [];
      if(val[0] == '1') {
        dateRange = timeSag.day;
      } 
      if(val[0] == '2') {
        dateRange = timeSag.week;
      } 
      if(val[0] == '3') {
        dateRange = timeSag.month;
      } 
      if(val[0] == '4') {
        dateRange = timeSag.year;
      }
      if(val[0] == '5') {
        dateRange = val[1];
      } 

      obj = {
        ...obj,
        [key]: { CREATEDATE : dateRange }
      };
    } else {
      obj = {
        ...obj,
        [key]: val
      };
    }
    
    this.setState({ formValue: obj });
  }

  deleteRecords = (msg, onOk, onCancel) => {
    Modal.confirm({
      title: getLabel('131329','信息确认'),
      content: msg,
      onOk() {
        typeof onOk === 'function' && onOk();
      },
      onCancel() {
        typeof onCancel === 'function' && onCancel();
      },
    });
  }

  render() {
    let { recentBrowsing } = this.state;
    let { ecodeTitleParams, tagsDatas:{commonConditions, }, getConditionSetTable } = this.props.weesoStore;
    ecodeTitleParams = toJS(ecodeTitleParams);
    commonConditions = toJS(commonConditions);

    const { getCustompageBaseDatas, page_uuid, homeLoading, delHistorySearch, getSearchTagList, setState } = this.props.weesoSeachSetStore;
    let { baseDatas:{ page_showCommonConditions, page_showHistory } } = this.props.weesoSeachSetStore;
    let H = window.innerHeight * 0.33;
    const { prefixCls } = this.props;
    let rowStyle = {
      className: "esearch-tags-col-2",
    },
    colStyle = {
      offset: '0',
      span: "12"
    }, 
    cardWidth = 393;

    if(!(page_showCommonConditions && page_showHistory)) { // 单行显示
      rowStyle = {
        className: "esearch-tags-col-1",
        type: "flex",
        justify: "center"
      };
      colStyle = {};
      cardWidth = 428;
    }
    let { historySearchList, tagList } = this.props.weesoStore;
    historySearchList = toJS(historySearchList);
    tagList = toJS(tagList);

    return(
      <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@2pn6rx`} className="esearch-tags">
        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@jzvyu0`} spinning={homeLoading}>
          <div className={`${prefixCls}`} ref={this.cardContentRef}>
            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@i9y6kd`} {...rowStyle}> 
              {page_showHistory && <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@n1c8ej`} {...colStyle}>
                <Card ecId={`${this && this.props && this.props.ecId || ''}_Card@ysx2sk`} 
                  title={getLabel('503436','历史搜索') }
                  className={`${prefixCls}-left`}
                  style={{ width: cardWidth, height: 315, float: 'right' }}
                  extra={
                    <span className={`${prefixCls}-head-icon`}>
                      <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@sfqijr`} placement="bottom" title={getLabel('354','刷新') }>
                        <i className="icon-coms-Synchro" onClick={() => { 
                          getCustompageBaseDatas({
                            page_uuid: page_uuid,
                            cuspage_type: '2'
                          });
                        }}/>
                      </Tooltip>
                      <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@otbmwm`} placement="bottom" title={getLabel('91','删除') }>
                        <i className="icon-coms-delete" onClick={() => { this.deleteRecords(getLabel('524271','确定要清空历史搜索记录吗？') , () => {
                          delHistorySearch({ forAll: 1 }, () => {
                            getCustompageBaseDatas({
                              page_uuid: page_uuid,
                              cuspage_type: '2'
                            });
                          });
                        }) }}/>
                      </Tooltip>
                    </span>
                  }
                >
                  {
                    this.setTags(historySearchList, 'recentBro')
                  }
                </Card>
              </Col>}

              {page_showCommonConditions && <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@qhjcd8`} {...colStyle}>
                <Card ecId={`${this && this.props && this.props.ecId || ''}_Card@a19s51`} 
                  title={getLabel('32905','常用条件') }
                  className={`${prefixCls}-right`}
                  style={{ width: cardWidth, height: 315 }}
                  extra={
                    <span className={`${prefixCls}-head-icon`}>
                      <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@yetm18`} placement="bottom" title={getLabel('354','刷新') }>
                        <i className="icon-coms-Synchro" onClick={() => { 
                          getCustompageBaseDatas({
                            page_uuid: page_uuid,
                            cuspage_type: '3'
                          });
                        }}/>
                      </Tooltip>
                      <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@tofwnb`} placement="bottom" title={getLabel('524085','常用条件设置') }>
                        <i className="icon-coms-Flow-setting" onClick={() => {
                          let formValue = this.state.formValue;
                          formValue = {
                            ...formValue,
                            keywords: ''
                          };
                          getSearchTagList({
                            page_uuid: page_uuid,
                          }, () => {
                            setState({ recordId: '' });
                            this.setState({lvisible: true, formValue: formValue});
                          });
                        }}/>
                      </Tooltip>
                    </span>
                  }
                >
                  {
                    this.setTags(tagList)
                  }
                </Card>
              </Col>}
            </Row>

            {this.setMaintanceKey()}
          </div>
        </Spin>
      </Row>
    );
  }
}